package com.kfm.login.service.impl;

import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.kfm.login.service.SendEmailService;
import com.kfm.login.util.LoginUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class SendEmailServiceImpl implements SendEmailService {

    @Value("${login.email.password}")
    private String password;
    @Value("${login.email.user}")
    private String user;
    @Value("${login.email.host}")
    private String host;
    @Value("${login.email.port}")
    private Integer port;

    @Override
    public String sendCode(String target, Integer number) {
        String code = LoginUtils.randCode(number);
        sendMessage(target, "验证码", code, false);
        return code;
    }

    @Override
    public void send(String target, String message) {
        log.info("发送邮件：" + message);
        sendMessage(target, "异地登录提醒", message, false);
    }

    /**
     * 发送邮件
     * @param target 目标邮箱地址
     * @param subject 主题
     * @param content 内容
     * @param isHtml 是否是html
     */
    private void sendMessage(String target, String subject, String content, boolean isHtml) {
        MailAccount account = new MailAccount();
        account.setHost(host);
        account.setPort(port); // SMTP 服务器端口
        account.setAuth(true); // 启用身份验证
        account.setFrom(user);
        account.setUser(user); // 发件人邮箱地址
        account.setPass(password); // 发件人邮箱密码 获取授权码

        // 发送邮件
        MailUtil.send(account, List.of(target), subject, content, isHtml);
        log.info("邮件发送成功");
    }
}
